package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.ReadersService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Notice;
import com.joint.core.entity.manage.NoticeQuery;
import com.joint.core.entity.manage.Registe;
import com.joint.core.service.NoticeQueryService;
import com.joint.core.service.NoticeService;
import com.joint.core.service.RegisteService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;


@ParentPackage("manage")
public class AjaxRegisteAction extends BaseFlowAction {
    @Resource
    private RegisteService registeService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private ReadersService readersService;

    /**
     * 资料登记表对象(读)
     */
    private Registe registe;

    /**
     * 登录人(读)
     */
    private Users loginUser;
    /**
     * 附件上传Id(读)
     */
    private String fileId;

    /**
     * 资料登记（读）
     */
    private List<Map<String, Object>> typeDict;

    /**
     *  资料类别
     */
    private String typedictId;

    /**
     *  资料说明
     */
    private String dataExplain;

    /**
     * 资料名称
     */
    private String dataName;

    /**
     * 附件上传Id
     */
    private String fileIds;
    /**
     * 视图类型
     */
    private String viewtype;


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "registe";
    }



    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        if(viewtype !=null && viewtype.equals("2")){
            pager.setOrderBy("modifyDate");
        }
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();

        params = getSearchFilterParams(_search,params,filters);

        /*内嵌视图这里要加上
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(parentId)){
            manageProInfo = manageProInfoService.get(parentId);
            params.put("manageProInfo",manageProInfo);
        }*/
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
      //  LogUtil.info("viewtype:" + viewtype);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("invalid", false);
                pager=registeService.findByPagerAndLimit(false, "registe", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("invalid", false);
                pager=registeService.findByPagerAndFinish( "registe", pager, params);
            }else if(viewtype.equals("3")){
                //已失效
                params.put("invalid", true);
                pager=registeService.findByPagerAndLimit(true, "registe", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=registeService.findByPagerAndLimit(true, "registe", pager, params);
        }

        List<Registe> registeList;
        if (pager.getTotalCount() > 0){
            registeList = (List<Registe>) pager.getList();
        }else{
            registeList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Registe registe: registeList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",registe.getId());
            rMap.put("type",registe.getType() != null?registe.getType().getName():"");
            rMap.put("dataName",registe.getDataName());
            rMap.put("creater", registe.getCreater() != null ? registe.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(registe.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("modifyDate", DataUtil.DateToString(registe.getModifyDate(),"yyyy-MM-dd"));
            rMap.put("state",registe.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }



    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            fileId ="";
            registe = registeService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            if(registe.getFile() != null && registe.getFile().size()>0){
                for(FileManage f:registe.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "read";
    }

    public String input(){
      //  loginUser = usersService.getLoginInfo();
        Company company = usersService.getCompanyByUser();
        List<Dict> dataType = dictService.listFormDefinedEnable(DictBean.DictEnum.DataType, company.getId());
        Map<String,Object> rMap = null;
        typeDict = new ArrayList<Map<String, Object>>();
        if (StringUtils.isNotEmpty(keyId)){
            fileId ="";
            registe = registeService.get(keyId);
            if(registe.getFile() != null && registe.getFile().size()>0){
                for(FileManage f:registe.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            for(Dict typeObj:dataType){
                rMap = new HashMap<String, Object>();
                rMap.put("id",typeObj.getId());
                rMap.put("name",typeObj.getName());
                rMap.put("selected","");
                if(registe.getType()!=null && StringUtils.equals(typeObj.getId(), registe.getType().getId())){
                    rMap.put("selected","selected");
                }
                typeDict.add(rMap);
            }
        } else {
            for(Dict typeObj:dataType){
                rMap = new HashMap<String, Object>();
                rMap.put("id",typeObj.getId());
                rMap.put("name",typeObj.getName());
                rMap.put("selected","");
                typeDict.add(rMap);
            }

        }

        return "input";
    }

    private void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            registe = registeService.get(keyId);
        }else{
            registe = new Registe();
            registe.setCreater(usersService.getLoginInfo());
        }
        registe.setDataExplain(dataExplain);
        if(StringUtils.isNotEmpty(typedictId)){
            registe.setType(dictService.get(typedictId));
        }
        registe.setDataName(dataName);
        List<FileManage> fileManageList = Lists.newArrayList();
        if(com.joint.base.util.StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManageService.get(f.trim()));
            }
        }
        registe.setFile(fileManageList);
        registe.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                registeService.update(registe);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                registeService.save(registe, "registe", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Company company = usersService.getCompanyByUser();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                registeService.approve(registe, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = registeService.commit(registe, "registe", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        registe = registeService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                registeService.approve(registe, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            registe = registeService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("registe");
            String key= activityList.get(activityList.size()-1).getId();
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            registeService.deny(registe, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    /**
     * 失效
     * @return
     */
    public String doInvalid(){
        if(StringUtils.isNotEmpty(keyId)) {
            registe = registeService.get(keyId);
            registe.setInvalid(true);
            registeService.update(registe);
        }
        return ajaxHtmlCallback("200", "操作成功！", "操作状态");
    }

    public Registe getRegiste() {
        return registe;
    }

    public void setRegiste(Registe registe) {
        this.registe = registe;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public List<Map<String, Object>> getTypeDict() {
        return typeDict;
    }

    public void setTypeDict(List<Map<String, Object>> typeDict) {
        this.typeDict = typeDict;
    }

    public String getTypedictId() {
        return typedictId;
    }

    public void setTypedictId(String typedictId) {
        this.typedictId = typedictId;
    }

    public String getDataExplain() {
        return dataExplain;
    }

    public void setDataExplain(String dataExplain) {
        this.dataExplain = dataExplain;
    }

    public String getDataName() {
        return dataName;
    }

    public void setDataName(String dataName) {
        this.dataName = dataName;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }
}

